package com.servlet;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.beanutils.BeanUtils;

import com.domain.User;
import com.service.userService;

/**
 * 
 * 
 * 功能描述：登录Servlet
 * 
 * Version： 1.0
 * 
 * date： 2016年6月22日 上午11:21:48
 * 
 * @author：XiaoBingBy
 *
 */
public class loginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	public loginServlet() {
		super();
	}

	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		User myUser = new User();// JavaBean

		// 把数据封装到Bean中
		try {
			BeanUtils.populate(myUser, request.getParameterMap());
		} catch (IllegalAccessException e) {
			e.printStackTrace();
		} catch (InvocationTargetException e) {
			e.printStackTrace();
		}

		// 做登录是否成功跳转
		userService userService = new userService();
		User isLogin = userService.isLoginService(myUser);
		if (isLogin != null) {
			// 登录成功 把我的用户信息存session 并 重定向
			HttpSession session = request.getSession();
			session.setAttribute("MyUser", isLogin);
			System.out.println("登录成功");
			response.sendRedirect(request.getContextPath() + "/user/userinfo.jsp");
			//TODO  其他页面还需要做取用户信息
			
		} else {
			// 登录失败做转发
			System.out.println("登录失败");
			//TODO 做用户体验，登录失败提示
			request.getRequestDispatcher("/login.jsp").forward(request, response);
		}

	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
	}

}
